import { AxiosError, AxiosResponse } from "axios";
import { tokenUtils } from "../token";
import { RequestConfig, RequestResult } from "@/types/custom/request";
import {
  REQUEST_SUCCESS_CODE,
  REQUEST_AUTHORIZATION,
  REFRESH_TOKEN_CODES,
  handleAxiosError,
  handleBackendError,
  handleResponseError,
} from "./service";
import { useAuthStore } from "@/store";

/** 请求拦截 */
export const reqResolve = (config: RequestConfig) => {
  // 处理不需要token的请求
  if (config.noNeedToken) return config;

  const token = tokenUtils.get();
  if (!token) {
    return Promise.reject(new AxiosError("登录已过期，请重新登录！", "401"));
  }

  // 加上 token
  if (!config.headers) config.headers = {};
  config.headers[REQUEST_AUTHORIZATION] = token;

  return config as any;
};

/** 请求错误拦截 */
export const reqReject = (axiosError: AxiosError) => {
  const error = handleAxiosError(axiosError);
  return Promise.reject(error);
};

/** 响应拦截 */
export const resResolve = (response: AxiosResponse): any => {
  const { data, status } = response;
  // 先处理error情况
  if (status >= 300 && status !== 304) {
    const error = handleResponseError(response);
    return Promise.reject(error);
  }

  const result = data as RequestResult;
  // 请求成功
  if (result.code === REQUEST_SUCCESS_CODE) {
    return Promise.resolve(data);
  }

  // token失效
  if (REFRESH_TOKEN_CODES.includes(result.code)) {
    useAuthStore().reLogin();
  }

  const error = handleBackendError(response);
  return Promise.reject(error);
};

/** 响应错误拦截 */
export const resReject = (axiosError: AxiosError) => {
  const error = handleAxiosError(axiosError);
  return Promise.reject(error);
};
